package classign.election.kingvar.come.electionclasssign.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;

import com.dl7.tag.TagView;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import classign.election.kingvar.come.electionclasssign.R;
import classign.election.kingvar.come.electionclasssign.api.RetrofitService;
import classign.election.kingvar.come.electionclasssign.api.info.BaseClassInfo;
import classign.election.kingvar.come.electionclasssign.base.BaseActivity;
import classign.election.kingvar.come.electionclasssign.tools.bean.User;
import classign.election.kingvar.come.electionclasssign.tools.utils.RxHelper;
import classign.election.kingvar.come.electionclasssign.tools.utils.ToastUtils;
import rx.Subscriber;
import rx.Subscription;

import static classign.election.kingvar.come.electionclasssign.tools.utils.Constants.MY_PERMISSION_REQUEST_CODE;


/**
 * @author 鞠永强
 * @version $Rev$
 * @time 2017/1/13 0013 9:35
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDate $Date$
 * @updateDes ${TODO}
 */

public class SplashActivity extends BaseActivity {
    private static final String TAG = "SplashActivity";
    @BindView(R.id.tag_skip)
    TagView mTagSkip;
    private boolean mIsSkip = false;
    private Subscription subscription;

    @Override
    public void onRoot(Bundle savedInstanceState) {
        setContentView(R.layout.activity_splash);
    }

    @Override
    protected void initInjector() {
        if (User.getImei(SplashActivity.this) == null || "".equals(User.getImei(SplashActivity.this))) {
            Log.i(TAG, "initInjector: 888888888888");
            finish();
            Intent intent = new Intent(this, BandingDeviceIdActivity.class);
            startActivity(intent);
        } else {
            RetrofitService.getBaseClassInfo(User.getImei(SplashActivity.this))
                    .subscribe(new Subscriber<BaseClassInfo>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            Logger.e(e.toString());

                        }

                        @Override
                        public void onNext(BaseClassInfo baseClassInfo) {
                            if (baseClassInfo.getCode() == 1) {
                                ToastUtils.showToast("设备未绑定,获取设备唯一标识码中....");
                                finish();
                                Intent intent = new Intent(SplashActivity.this, BandingDeviceIdActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.hold, R.anim.zoom_in_exit);
                            } else if (baseClassInfo.getCode() == 0) {
                                Log.i(TAG, "onNext: 999999999999999");
                                BaseClassInfo.InfoEntity infoBeen = baseClassInfo.getInfo();
                                User.setClassId(SplashActivity.this, infoBeen.getClsid());
                                User.setClassMonitor(SplashActivity.this, infoBeen.getMonitor());
                                User.setClassTeacherOne(SplashActivity.this, infoBeen.getName());
                                User.setClassTeacherTwo(SplashActivity.this, infoBeen.getViceName());
                                User.setSchoolId(SplashActivity.this, infoBeen.getSchoolid() + "");
                                User.setClassName(SplashActivity.this, infoBeen.getCname());
                                User.setUserID(SplashActivity.this, infoBeen.getId() + "");
                                aboutPermission();
                            }else {
                                aboutPermission();
                            }
                        }
                    });
        }
    }

    @Override
    protected void initView() {

    }


    @Override
    public void initData() {
    }

    private void aboutPermission() {
        boolean isAllGranted = checkPermissionAllGranted(
                new String[]{
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CHANGE_WIFI_STATE
                }
        );
        if (isAllGranted) {
            updateViews();
            return;
        }
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE
               }, MY_PERMISSION_REQUEST_CODE);
    }

    @Override
    public void initListener() {
        mTagSkip.setTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int pos, String text, int mode) {
                _doSkip();
            }
        });
    }

    @Override
    public void WidgetClick(View view) {

    }

    /**
     * 数据同步 倒计时
     */
    private void updateViews() {
        subscription = RxHelper.countdown(5)
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        _doSkip();
                    }

                    @Override
                    public void onError(Throwable e) {
                        _doSkip();
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mTagSkip.setText("跳过 " + integer);
                    }
                });
    }


    private void _doSkip() {
        if (!mIsSkip) {
            mIsSkip = true;
            finish();
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            overridePendingTransition(R.anim.hold, R.anim.zoom_in_exit);
        }
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "checkPermissionAllGranted: 123" + permission);
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;

            }
        }
        return true;
    }

    /**
     * 第 3 步: 申请权限结果返回处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行备份代码
                updateViews();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
                openAppDetails();
            }
        }
    }

    /**
     * 打开 APP 的详情设置
     */
    private void openAppDetails() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("获取班牌的id号，请到 “应用信息 -> 权限” 中授予！");
        builder.setPositiveButton("去手动授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                aboutPermission();
            }
        });
        builder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }
}
